﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using Database.Classes;
using System.Collections.Generic;


public partial class StoredProcedures
{
    public static Dictionary<int, int> TABonuses()
    {
        Dictionary<int, int> tmp = new Dictionary<int, int>();
        List<int> players = UserDefinedFunctions.GetPlayerIDs();
        foreach (int i in players)
            tmp.Add(i, TABonus(i));
        return tmp;
    }
    public static List<int> TAPartners(int UserId)
    {
        List<int> partners = new List<int>();
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(@"Select * From Agreements Where (pId1 = @p or pId2 = @p) and Type = 0 and Status = 1", conn))
            {
                cmd.Parameters.Add("@p", SqlDbType.Int).Value = UserId;
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    if (reader.GetInt32(0) != UserId) partners.Add(reader.GetInt32(0));
                    if (reader.GetInt32(1) != UserId) partners.Add(reader.GetInt32(1));
                }
            }
        }
        return partners;
    }
    public static int TABonus(int UserId)
    {
        int bonus = 0;
        List<int> partners = TAPartners(UserId);
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            foreach (int uId in partners)
            {
                using (SqlCommand cmd = new SqlCommand(@"Select Count(*) From Planets Where OwnerID = @p PopulationLevel >= 10", conn))
                {
                    cmd.Parameters.Add("@p", SqlDbType.Int).Value = uId;
                    bonus += int.Parse(cmd.ExecuteScalar().ToString());
                }
            }
        }
        return bonus;
    }
    public static int TACost(int UserId)
    {
        return 20000;
    }
    public static int NumberOfTA(int UserId)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(@"Select Count(*) From Agreements Where (pId1 = @p or pId2 = @p) and Type = 0", conn))
            {
                cmd.Parameters.Add("@p", SqlDbType.Int).Value = UserId;
                return int.Parse(cmd.ExecuteScalar().ToString());
            }
        }
    }
    public static int NumberOfSA(int UserId)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(@"Select Count(*) From Agreements Where (pId1 = @p or pId2 = @p) and Type = 1", conn))
            {
                cmd.Parameters.Add("@p", SqlDbType.Int).Value = UserId;
                return int.Parse(cmd.ExecuteScalar().ToString());
            }
        }
    }
    public static int NumberOfAgreements(int UserId, int type)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(@"Select Count(*) From Agreements Where (pId1 = @p or pId2 = @p) and Type = @t", conn))
            {
                cmd.Parameters.Add("@p", SqlDbType.Int).Value = UserId;
                cmd.Parameters.Add("@t", SqlDbType.Int).Value = type;

                return int.Parse(cmd.ExecuteScalar().ToString());
            }
        }
    }
    public static int SACost()
    {
        return 30000;
    }
    public static int AgreementStatus(int p1, int p2, int type)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(@"Select Status From Agreements Where (pId1 = @p1 and pId2 = @p2) and Type = @t", conn))
            {
                cmd.Parameters.Add("@p1", SqlDbType.Int).Value = p1;
                cmd.Parameters.Add("@p2", SqlDbType.Int).Value = p2;
                cmd.Parameters.Add("@t", SqlDbType.Int).Value = type;

                object o = cmd.ExecuteScalar();
                if (o != null && o.ToString() != string.Empty)
                    return int.Parse(o.ToString());
                else
                {//try the other way
                    cmd.CommandText = @"Select Status From Agreements Where (pId1 = @p2 and pId2 = @p1) and Type = @t";
                    o = cmd.ExecuteScalar();
                    if (o != null && o.ToString() != string.Empty)
                        return int.Parse(o.ToString());
                    else
                        return -1;
                }
            }
        }
    }
    public static int Cost(int UserId, int type)
    {
        switch (type)
        {
            case 0: return TACost(UserId);
            case 1: return SACost();
            default: return 0;
        }
    }
    [SqlProcedure()]
    public static bool SendAgreement(int from, int to, int type)
    {
        if (type == 0)
        {
            if (NumberOfTA(from) >= 5 || NumberOfTA(to) >= 5)
                return false;
        }
        else if (type == 1)
        {
            if (NumberOfSA(from) >= 1 || NumberOfSA(to) >= 1)
                return false;
        }
        if (from == to)
            return false;
        int cost = Cost(from, type);
        if (UserDefinedFunctions.GetPlayerCash(from).ToSqlInt32().Value < cost)
            return false;
        if (AgreementStatus(from, to, type) != -1)
            return false;
        bool insertSucces = false;
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(@"Insert Into Agreements Values (@p1, @p2, 0, @t)", conn))
            {
                cmd.Parameters.Add("@p1", SqlDbType.Int).Value = from;
                cmd.Parameters.Add("@p2", SqlDbType.Int).Value = to;
                cmd.Parameters.Add("@t", SqlDbType.Int).Value = type;

                if (cmd.ExecuteNonQuery() > 0)
                    insertSucces = true;

                cmd.CommandText = "Update Players set Cash = Cash - @p Where PlayerId = @p1";
                cmd.Parameters.Add("@p", SqlDbType.Int).Value = cost;
            }
        }
        if (insertSucces == true)
        {
            switch (type)
            {
                case 0:
                    InsertNews(to, DateTime.Now, "Player <a href=\"PlayerInfo.aspx?pId=" + from.ToString() + "\">" + UserDefinedFunctions.PlayerName(from) + "</a> send you trade cooperation offer.<br/> You may accept it on Agreements screen.");
                    break;
                case 1:
                    InsertNews(to, DateTime.Now, "Player <a href=\"PlayerInfo.aspx?pId=" + from.ToString() + "\">" + UserDefinedFunctions.PlayerName(from) + "</a> send you science cooperation offer.<br/> You may accept it on Agreements screen.");
                    break;
            }
            return true;
        }
        return false;
    }
    public static bool RejectAgreement(int from, int to, int type)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(@"Delete From Agreements Where Status = 0 Where pId1 = @p1 and pId2 = @p2 and Type = @t)", conn))
            {
                cmd.Parameters.Add("@p1", SqlDbType.Int).Value = from;
                cmd.Parameters.Add("@p2", SqlDbType.Int).Value = to;
                cmd.Parameters.Add("@t", SqlDbType.Int).Value = type;
                cmd.ExecuteNonQuery();
            }
        }
        return true;
    }
    public static bool AcceptAgreement(int from, int to, int type)
    {
        int cost = Cost(to, type);
        if (UserDefinedFunctions.GetPlayerCash(to).ToSqlInt32().Value < cost)
            return false;
        int status = AgreementStatus(from, to, type);
        if (status != 0)
            return false;
        else
        {//ready to accept
            bool updateSuccess = false;
            using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(@"Update Agreements Set Status = 1 Where pId1 = @p1 and pId2 = @p2 and Type = @t)", conn))
                {
                    cmd.Parameters.Add("@p1", SqlDbType.Int).Value = from;
                    cmd.Parameters.Add("@p2", SqlDbType.Int).Value = to;
                    cmd.Parameters.Add("@t", SqlDbType.Int).Value = type;

                    if (cmd.ExecuteNonQuery() > 0)
                        updateSuccess = true;
                    cmd.CommandText = "Update Players set Cash = Cash - @p Where PlayerId = @p2";
                    cmd.Parameters.Add("@p", SqlDbType.Int).Value = cost;

                }
            }
            if (updateSuccess == true)
            {
                InsertNews(from, DateTime.Now, "Player <a href=\"PlayerInfo.aspx?pId=" + to.ToString() + "\">" + UserDefinedFunctions.PlayerName(to) + "</a> accepted your agreement offer.");
                return true;
            }
        }
        return false;
    }
};
